package lookie.swing.laf;

import java.util.HashSet;
import java.util.Set;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class LookAndFeelConfigurer {
	
	private Set<LookAndFeelConfigurerListener> listeners = new HashSet<LookAndFeelConfigurerListener>();
	
	private LookAndFeelDescriptor currentDescriptor;
	
	public LookAndFeelDescriptor getCurrentDescriptor() {
		return currentDescriptor;
	}

	public void addListener(LookAndFeelConfigurerListener listener) {
		listeners.add(listener);
	}
	
	public void removeListener(LookAndFeelConfigurerListener listener) {
		listeners.remove(listener);
	}
	
	public void configure(LookAndFeelDescriptor descriptor) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
		
			UIManager.setLookAndFeel(descriptor.getClassName());
			currentDescriptor = descriptor;
	}
	
	public void configureAndUpdate(LookAndFeelDescriptor descriptor) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
		LookAndFeelDescriptor oldDescriptor = currentDescriptor;
		configure(descriptor);
		notifyListeners(oldDescriptor, currentDescriptor);
	}

	private void notifyListeners(LookAndFeelDescriptor oldDescriptor,
			LookAndFeelDescriptor newDescriptor) {
		for (LookAndFeelConfigurerListener listener : listeners) {
			listener.update(oldDescriptor, newDescriptor);
		}
	}

}
